package main.java.com.fei.springboot.controller;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import main.java.com.fei.springboot.bean.BootResponse;
import main.java.com.fei.springboot.domain.User;
import main.java.com.fei.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.java2d.cmm.CMSManager;

/***
 * 用户模块
 */
@Api(description = "用户模块", tags = {"用户模块接口控制层"})
@RequestMapping("/user")
@RestController
public class UserController {

	
	@Autowired
	UserService userService;


	/**
	 * 添加账号
	 * @param user
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/v1/addUser")
	@ApiOperation(value = "添加账号", httpMethod = "POST", response = BootResponse.class)
	public BootResponse addUser(@RequestBody User user) throws Exception {
		userService.insertUser(user);
		return new BootResponse();
	}


	/**
	 * 获取一个用户
	 * @param id
	 * @return
	 */
	@GetMapping("/get/{id}")
	@ApiOperation(value = "根据ID取一个用户", httpMethod = "GET", response = BootResponse.class)
	public BootResponse findById(@PathVariable("id") String id){
		User u = this.userService.findById(id);
		return new BootResponse(u);
	}


	/**
	 * 测试写然后读
	 * @param id
	 * @param userName
	 * @return
	 */
	@GetMapping("/addAndRead/{id}/{userName}")
	@ApiOperation(value = "测试写然后读取该用户", httpMethod = "GET", response = BootResponse.class)
	public BootResponse addAndRead(@PathVariable String id,@PathVariable String userName){
		User u = new User();
		u.setId(id);
		u.setUserName(userName);
		this.userService.wirteAndRead(u);
		return new BootResponse(u.getUserName());
	}
	
	/**
	 * 测试读然后写
	 * @param id
	 * @param userName
	 * @return
	 */
	@GetMapping("/readAndAdd/{id}/{userName}")
	@ApiOperation(value = "测试读然后写用户", httpMethod = "GET", response = BootResponse.class)
	public BootResponse readAndWrite(@PathVariable String id,@PathVariable String userName){
		User u = new User();
		u.setId(id);
		u.setUserName(userName);
		this.userService.readAndWirte(u);
		return new BootResponse(u.getUserName());
	}
	
	/**
	 * 测试分页插件
	 * @return
	 */
	@GetMapping("/queryPage")
	@ApiOperation(value = "测试分页插件", httpMethod = "GET", response = BootResponse.class)
	public BootResponse queryPage(){
		PageInfo<User> page = this.userService.queryPage( 0, 10);
		StringBuilder sb = new StringBuilder();
		sb.append("<br/>总页数=" + page.getPages());
		sb.append("<br/>总记录数=" + page.getTotal()) ;
		for(User u : page.getList()){
			sb.append("<br/>" + u.getId() + "      " + u.getUserName());
		}

		System.out.println("分页查询....\n" + sb.toString());
		return new BootResponse(sb.toString());
	}
	
}
